from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from api.logic.wechat import WechatLogic
from api.models.feedback import Feedback
from api.utils.jwt_utils import verify_token
from api.utils.response import success_response, error_response
from api.utils.log_utils import log_operation
from api.utils.pagination import paginate_queryset
import json

@csrf_exempt
@require_http_methods(["POST"])
def feedback_create(request):
    """提交反馈意见"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        wechat_logic = WechatLogic()
        user = wechat_logic.get_user_by_token(token)
        user_id = user.id
        if not user_id:
            return error_response('未登录或登录已过期')
            
        # 解析请求数据
        data = json.loads(request.body)
        feedback_type = data.get('feedback_type')
        content = data.get('content')
        contact = data.get('contact')
        images = data.get('images', [])
        
        if not feedback_type or not content:
            return error_response('反馈类型和内容不能为空')
            
        # 创建反馈
        feedback = Feedback.objects.create(
            user_id=user_id,
            feedback_type=feedback_type,
            content=content,
            contact=contact
        )
        feedback.set_images(images)
        feedback.save()
        
        # 记录操作日志
        log_operation(user, 'create_feedback', f'提交反馈：{feedback.get_feedback_type_display()}')
        
        return success_response(feedback.to_dict())
    except json.JSONDecodeError:
        return error_response('无效的请求数据')
    except Exception as e:
        return error_response(f'提交反馈失败：{str(e)}')

@require_http_methods(["GET"])
def feedback_list(request):
    """获取反馈列表"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        user_id = verify_token(token)
        if not user_id:
            return error_response('未登录或登录已过期')
            
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        
        # 获取筛选参数
        feedback_type = request.GET.get('feedback_type')
        status = request.GET.get('status')
        
        # 构建查询
        queryset = Feedback.objects.filter(user_id=user_id)
        
        # 应用筛选
        if feedback_type:
            queryset = queryset.filter(feedback_type=feedback_type)
        if status:
            queryset = queryset.filter(status=status)
            
        # 分页
        result = paginate_queryset(queryset, page, size)
        
        # 格式化数据
        feedback_list = [feedback.to_dict() for feedback in result['items']]
        
        return success_response({
            'list': feedback_list,
            'total': result['total'],
            'page': result['page'],
            'size': result['size'],
            'pages': result['pages']
        })
    except Exception as e:
        return error_response(f'获取反馈列表失败：{str(e)}')

@require_http_methods(["GET"])
def feedback_detail(request, feedback_id):
    """获取反馈详情"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        user_id = verify_token(token)
        if not user_id:
            return error_response('未登录或登录已过期')
            
        # 获取反馈详情
        try:
            feedback = Feedback.objects.get(id=feedback_id, user_id=user_id)
        except Feedback.DoesNotExist:
            return error_response('反馈不存在', 404)
            
        return success_response(feedback.to_dict())
    except Exception as e:
        return error_response(f'获取反馈详情失败：{str(e)}') 